import 'dart:convert';

import 'package:hotpot/models/account_move.dart';
import 'package:hotpot/models/loyalty_card.dart';
import 'package:hotpot/models/product.dart';
import 'package:hotpot/models/product_public_category.dart';
import 'package:hotpot/models/product_ribbon.dart';
import 'package:hotpot/models/res_country.dart';
import 'package:hotpot/models/res_country_state.dart';
import 'package:hotpot/models/res_partner.dart';
import 'package:hotpot/models/sale_order.dart';
import 'package:hotpot/models/sale_order_line.dart';
import 'package:hotpot/models/stock_picking.dart';
import 'package:hotpot/odoo/odoo_helper.dart';

abstract class OdooApi {
  /// 检测邮箱是否存在
  static Future<bool> checkEmail(String email) async {
    var data = await OdooHelper.search(
      'res.users',
      domain: {'email': email},
      fields: ['id'],
    );
    return data is List && data.isEmpty;
  }

  /// 检测邮箱是否存在
  static Future<bool> checkMobile(String mobile) async {
    var data = await OdooHelper.search(
      'res.users',
      domain: {'mobile': mobile},
      fields: ['id'],
    );
    return data is List && data.isEmpty;
  }

  /// 注册
  static Future<int> register(String name, String email, String mobile, String barcode) async {
    var data = await OdooHelper.create(
      'res.users',
      arg: {
        'name': name,
        // 'email': email,
        // 'login': email,
        if (email.isNotEmpty) 'email': email,
        'login': mobile,
        'mobile': mobile,
        // 'password': psw,
        if (barcode.isNotEmpty) 'barcode': barcode,
        'groups_id': [10],
      },
      showLoading: true,
    );
    return data;
  }

  /// 获取商品列表
  static Future<List<Product>> getProductList(int pageNo, {bool isPublished = true, int? categoryId, String? searchText}) async {
    var data = await OdooHelper.search(
      'product.template',
      pageNo: pageNo,
      pageSize: 20,
      domainLike: {'name': searchText, 'default_code': searchText, 'barcode': searchText},
      domain: {'is_published': isPublished, 'categ_id': categoryId},
      fields: Product().toJson().keys.toList()..remove('shopNum'),
    );
    print(data);
    if (data is List) {
      return data.map((e) => Product.fromJson(e)).toList();
    }
    return [];
  }

  /// 获取ribbon列表
  static Future<List<ProductRibbon>> getRibbonList(List<String> ids) async {
    var data = await OdooHelper.search(
      'product.ribbon',
      domain: {'id': ids},
    );
    print(data);
    if (data is List) {
      return data.map((e) => ProductRibbon.fromJson(e)).toList();
    }
    return [];
  }

  /// 获取类型列表
  static Future<List<ProductPublicCategory>> getCategoryList() async {
    var data = await OdooHelper.search(
      'product.public.category',
      fields: ProductPublicCategory().toJson().keys.toList(),
    );
    print(data);
    if (data is List) {
      return data.map((e) => ProductPublicCategory.fromJson(e)).toList();
    }
    return [];
  }

  /// 获取销售订单详情
  static Future<SaleOrder?> getSaleOrder(int orderId) async {
    var data = await OdooHelper.search('sale.order', fields: SaleOrder().toJson().keys.toList(), domain: {'id': orderId});
    if (data is List && data.isNotEmpty) {
      return SaleOrder.fromJson(data.first);
    }
    return null;
  }

  /// 获取销售订单列表
  static Future<List<SaleOrder>> getSaleOrderList(int pageNo, List<String> statusList) async {
    var data = await OdooHelper.search(
      'sale.order',
      domainLike: {'state': statusList},
      fields: SaleOrder().toJson().keys.toList(),
      pageNo: pageNo,
      pageSize: 20,
    );
    print(jsonEncode(data.first));
    if (data is List) {
      return data.map((e) => SaleOrder.fromJson(e)).toList();
    }
    return [];
  }

  /// 获取销售订单列表
  static Future<List<SaleOrderLine>> getSaleOrderLine(int orderId) async {
    var data = await OdooHelper.search(
      'sale.order.line',
      domainLike: {'order_id': orderId},
      fields: SaleOrderLine().toJson().keys.toList(),
    );
    print(jsonEncode(data.first));
    if (data is List) {
      return data.map((e) => SaleOrderLine.fromJson(e)).toList();
    }
    return [];
  }

  /// 修改销售订单
  static Future<int> updateOrder(int orderId, {String? signature}) async {
    var data = await OdooHelper.update(
      'sale.order',
      id: orderId,
      arg: {
        if (signature != null) 'signature': signature,
      },
    );
    return data;
  }

  /// 创建销售订单
  static Future<int> createOrder(int partnerId, {String? signature}) async {
    var data = await OdooHelper.create(
      'sale.order',
      arg: {
        'partner_id': partnerId,
        if (signature != null) 'signature': signature,
      },
      showLoading: true,
    );
    return data;
  }

  /// 创建销售订单商品
  static Future<dynamic> createOrderLineList(int orderId, List<Product> list) async {
    var data = await OdooHelper.create(
      'sale.order.line',
      argList: list
          .map((e) => {
                'product_id': e.id!,
                'order_id': orderId,
                'name': e.name ?? '',
                'price_unit': e.listPrice ?? 0,
                'product_uom_qty': e.shopNum ?? 0,
              })
          .toList(),
    );
    print(data);
    return data;
  }

  /// 创建销售订单商品
  static Future<int> createOrderLine(int orderId, int productId, String name, double priceUnit) async {
    var data = await OdooHelper.create(
      'sale.order.line',
      arg: {
        'product_id': productId,
        'order_id': orderId,
        'name': name,
        'price_unit': priceUnit,
      },
      showLoading: true,
    );
    return data;
  }

  /// 创建pos订单
  static Future<int> createPosOrderOrder() async {
    var data = await OdooHelper.search('pos.order', pageSize: 10, pageNo: 1);
    // var data = await OdooHelper.create('pos.order');
    jsonEncode(data.first);
    print(data);
    var data1 = await OdooHelper.search('pos.order.line', domain: {'order_id': data.first['id']});
    print(data1);
    return data;
  }

  static Future<List<ResPartner>> getPartner({
    int? id,
    int? parentId,
    int? partnerId,
    int pageNo = 1,
    int pageSize = 1,
    List<int>? childIds,
  }) async {
    var data = await OdooHelper.search(
      'res.partner',
      domain: {
        if (id != null) 'id': id,
        if (parentId != null) 'parent_id': parentId,
        if (partnerId != null) 'partner_id': partnerId,
      },
      domainLike: {if (childIds?.isNotEmpty ?? false) 'id': childIds},
      fields: ResPartner().toJson().keys.toList()..remove('partner_id'),
      pageNo: pageNo,
      pageSize: pageSize,
    );
    if (data is List) {
      if (pageSize == 1 && data.isNotEmpty) {
        return [ResPartner.fromJson(data.first)];
      } else {
        return data.map((e) => ResPartner.fromJson(e)).toList();
      }
    }
    return [];
  }

  /// 卡包
  /// programType - 类型
  ///   loyalty - 积分
  ///   ewallet - 钱包
  ///   gift_card - 卡包
  static Future<LoyaltyCard> getLoyaltyCard({int? userId, String? programType, String? code}) async {
    var domain = {
      'partner_id': userId,
      'program_type': programType,
      'code': code,
    };
    var data = await OdooHelper.search(
      'loyalty.card',
      domain: domain..removeWhere((key, value) => value == null),
      fields: LoyaltyCard().toJson().keys.toList(),
      showLoading: false,
    );
    if (data is List && data.isNotEmpty) {
      return LoyaltyCard.fromJson(data.first as Map<String, dynamic>);
    }
    return LoyaltyCard();
  }

  /// 个人信息
  static Future<ResPartner?> getResPartner({int? id, String? barcode}) async {
    var data = await OdooHelper.search(
      'res.partner',
      domain: {
        if (id != null) 'id': id,
        if (barcode != null) 'barcode': barcode,
      },
      fields: ResPartner().toJson().keys.toList()..remove('partner_id'),
      showLoading: true,
    );
    if (data is List) {
      if (data.isNotEmpty) {
        return ResPartner.fromJson(data.first as Map<String, dynamic>);
      } else {
        return ResPartner();
      }
    }
    return null;
  }

  static Future<ResPartner?> getUser({String? barcode, int? userId}) async {
    var data = await OdooHelper.search(
      'res.users',
      domain: {
        if (barcode != null) 'barcode': barcode,
        if (userId != null) 'id': userId,
      },
      fields: ResPartner().toJson().keys.toList(),
    );
    if (data is List) {
      if (data.isNotEmpty) {
        return ResPartner.fromJson(data.first);
      } else {
        return ResPartner();
      }
    }
    return null;
  }

  /// 获取发货单
  static Future<StockPicking?> getStockPicking(int orderId) async {
    var data = await OdooHelper.search(
      'stock.picking',
      domain: {'sale_id': orderId},
    );
    if (data is List && data.isNotEmpty) {
      return StockPicking.fromJson(data.first);
    }
    return null;
  }

  /// 获取交货单
  static Future<List<AccountMove>> getAccountMove(int pageNo, {int pageSize = 20, int? orderId}) async {
    var data = await OdooHelper.search(
      'account.move',
      domain: {
        if (orderId != null) 'sale_id': orderId,
      },
      pageSize: pageSize,
      pageNo: pageNo,
    );
    if (data is List) {
      if (data.isNotEmpty && pageNo == 1) {
        return [AccountMove.fromJson(data.first)];
      } else {
        return data.map((e) => AccountMove.fromJson(e)).toList();
      }
    }
    return [];
  }

  /// 更新销售订单状态
  static Future<bool?> updateSaleOrderState(int orderId) async {
    try {
      var data = await OdooHelper.callMethod(
        'sale.order',
        'action_confirm',
        id: orderId,
        showLoading: true,
      );
      return data;
    } catch (_) {
      return null;
    }
  }

  /// 获取省份
  /// id - 国家id
  static Future<List<ResCountryState>> getResCountryState(int id) async {
    var data = await OdooHelper.search(
      'res.country.state',
      domain: {'country_id': id},
      showLoading: true,
    );
    if (data is List && data.isNotEmpty) {
      return data.map((e) => ResCountryState.fromJson(e)).toList();
    }
    return [];
  }

  /// 获取国家
  static Future<List<ResCountry>> getResCountry() async {
    var data = await OdooHelper.search(
      'res.country',
      showLoading: true,
    );
    if (data is List && data.isNotEmpty) {
      return data.map((e) => ResCountry.fromJson(e)).toList();
    }
    return [];
  }

  /// 修改信息
  static Future<bool> editPartner(
    int id, {
    String? companyName,
    String? email,
    String? vat,
    String? phone,
    String? street,
    String? zip,
    String? city,
    int? countryId,
    String? countryCode,
    int? stateId,
    String? barcode,
    String? image,
    String? mobile,
  }) async {
    var arg = {
      'company_name': companyName,
      'email': email,
      'vat': vat,
      'phone': phone,
      'street': street,
      'zip': zip,
      'city': city,
      'mobile': mobile,
      'country_id': countryId,
      'country_code': '$countryCode',
      'state_id': stateId,
      'image_128': image,
      'barcode': barcode,
    };
    var data = await OdooHelper.update(
      'res.partner',
      id: id,
      arg: arg..removeWhere((key, value) => value == null),
      showLoading: true,
    );
    print(data);
    return data;
  }

  /// 添加partner
  static Future<int> addPartner({
    String? companyName,
    String? email,
    String? vat,
    String? phone,
    String? street,
    String? zip,
    String? city,
    int? countryId,
    String? countryCode,
    int? stateId,
    String? image,
    int? parentId,
    String? name,
  }) async {
    var arg = {
      'company_name': companyName,
      'email': email,
      'vat': vat,
      'phone': phone,
      'street': street,
      'zip': zip,
      'city': city,
      'country_id': countryId,
      'country_code': '$countryCode',
      'state_id': stateId,
      'image_128': image,
      'parent_id': parentId,
      'name': name,
    };
    try {
      var data = await OdooHelper.create(
        'res.partner',
        arg: arg..removeWhere((key, value) => value == null),
        showLoading: true,
      );
      print(data);
      return data;
    } catch (e) {
      print(e);
      throw ArgumentError();
    }
  }
}
